package com.lzq.springblog.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.lzq.springblog.common.Result;
import com.lzq.springblog.common.ResultCode;
import com.lzq.springblog.exception.ApplicationException;
import com.lzq.springblog.model.CaptchaProperties;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
@Slf4j
@Tag(name = "验证码接口")
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    @Operation(description = "获取验证码")
    @GetMapping("/getCaptcha")
    public Result getCaptcha(HttpServletResponse response, HttpSession session) {
        //1.CREATE
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        log.info("生成的验证码:{}",lineCaptcha.getCode());
//        response.setContentType("image/jpeg");
        response.setHeader("Pragma","No-cache");
        //2.OUTPUT
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captchaProperties.getSession().getKey(),lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            response.getOutputStream().close();
        } catch (Exception e) {
            throw new ApplicationException(Result.failed(ResultCode.FAILED));
        }
        return Result.success(null);
    }

    @Operation(description = "校验验证码")
    @PostMapping("/check")
    public Result check(String captcha,HttpSession session) {
        log.info("接收到输入的验证码:{}",captcha);
        //1.is null
        if(!StringUtils.hasLength(captcha)) {
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.is correct
        if(!captcha.equals(session.getAttribute(captchaProperties.getSession().getKey()))) {
            return Result.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        Date sessionDate = (Date)session.getAttribute(captchaProperties.getSession().getDate());
        Long duration = System.currentTimeMillis()-sessionDate.getTime();
        if(duration>captchaProperties.getValidTime()){
            return Result.failed(ResultCode.FAILED_OUT_OF_TIME_LIMITS);
        }else{
            return Result.success(null);
        }
    }
}